<template>
  <div class="main">
    <div style="padding: 30px">
      <a-form layout="inline" :model="form" ref="formRef" size="small" style="margin-bottom: 10px" :rules="rules">
        <a-form-item>
          <a-radio-group v-model:value="form.radio" button-style="solid" @change="radioChange">
            <a-radio-button value="分">分</a-radio-button>
            <a-radio-button value="合">合</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item has-feedback name="inputValue"><a-input v-model:value="form.inputValue" placeholder="请输入" /></a-form-item>
        <a-form-item has-feedback name="datetime"
          ><a-date-picker show-time valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="form.datetime"
        /></a-form-item>
        <a-form-item>
          <a-button type="primary" @click="save" class="mr-2"> 查 询 </a-button>
          <a-button type="primary" @click="reset" class="mr-2"> 重 置 </a-button>
        </a-form-item>
      </a-form>

      <!-- <a-table class="atable" :columns="columns" :data-source="tableData1" :pagination="false" bordered /> -->
      <table class="myTable1" width="100%" border="0" cellpadding="0" cellspacing="0">
        <thead>
          <tr>
            <th>生产车间</th>
            <th>供料机</th>
            <th>日期</th>
            <th>班别</th>
            <th>检验员</th>
            <th>产品规格名称</th>
            <th>技术标准号</th>
            <th>班组负责人</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="bcData">
            <td>{{ bcData.productFloor }}</td>
            <td>{{ bcData.feeder }}</td>
            <td>{{ bcData.datetime }}</td>
            <td>{{ bcData.className }}</td>
            <td>{{ bcData.inspector }}</td>
            <td>{{ bcData.productSpecsName }}</td>
            <td>{{ bcData.skillStandardNumber }}</td>
            <td>{{ bcData.classHead }}</td>
          </tr>
          <tr v-else><td v-for="(item, index) in 8" :key="index" style="height: 50px"></td></tr>
        </tbody>
      </table>

      <div style="margin: 20px 0; display: flex">
        <div style="width: 60%; height: 100%; padding-right: 30px; display: flex; flex-direction: column">
          <img :src="dashbordTitle2" alt="jeecg" style="margin-bottom: 20px; width: 600px; height: 30px; object-fit: cover" />
          <table v-if="eqData" class="myTable" width="100%" border="0" cellpadding="0" cellspacing="0" style="height: 360px">
            <colgroup>
              </colgroup>
            <thead>
              <tr>
                <th style="width: 180px;"></th>
                <th v-for="(item, index) in eqData.times" :key="index">{{ item }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in eqData.data" :key="index">
                <td v-for="(item1, index1) in item" :key="index1" :style="index1==0?'width:180px;':''">{{ item1 }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div style="width: 40%; height: 100%; display: flex; flex-direction: column">
          <img :src="dashbordTitle3" alt="jeecg" style="margin-bottom: 20px; width: 600px; height: 30px; object-fit: cover" />
          <VisitAnalysis2 :height="'360px'" :chart-data="analysisData" />
        </div>
      </div>
      <div>
        <img :src="dashbordTitle4" alt="jeecg" style="margin-bottom: 20px; width: 600px; height: 30px; object-fit: cover" />
        <Bar :height="'300px'" :chart-data="barData" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';

  import dashbordTitle2 from '/@/assets/images/dashbord-title2.png';
  import dashbordTitle3 from '/@/assets/images/dashbord-title3.png';
  import dashbordTitle4 from '/@/assets/images/dashbord-title4.png';
  import VisitAnalysis2 from '@/views/dashboard/Analysis/components/VisitAnalysis2.vue';
  import Bar from '@/views/dashboard/Analysis/components/Bar.vue';
  import { queryAll, queryAll2, queryCount, queryCount2, queryEqPC, queryEqPC2, queryZkClassMessagePC } from './chart.api';

  onMounted(() => {});

  let barData = ref(null);
  let analysisData = ref(null);
  let bcData = reactive({});
  let eqData = reactive({ times: [], data: [] });

  const form = reactive({
    radio: '分',
    inputValue: '',
    datetime: '',
  });
  const formRef = ref(null);
  const validateInput = (_rule, value) => {
    if (value === '') {
      return Promise.reject('请输入!');
    } else {
      var reg1 = /\d+-\d+/;
      var reg2 = /\d+-\d+-\d+/;
      if (form.radio == '合') {
        if (!reg1.test(value)) {
          return Promise.reject('请输入1-1此类格式!');
        } else {
          return Promise.resolve();
        }
      } else if (form.radio == '分') {
        if (!reg2.test(value)) {
          return Promise.reject('请输入1-1-1此类格式!');
        } else {
          return Promise.resolve();
        }
      }
    }
  };
  const rules = {
    inputValue: [{ required: true, validator: validateInput, trigger: 'change' }],
    datetime: [{ required: true, message: '请选择', trigger: 'change' }],
  };

  // 分合切换事件
  function radioChange() {
    form.inputValue = '';
    form.datetime = '';
    formRef.value.resetFields();
  }

  // 查询
  async function save() {
    try {
      const valid = await formRef.value.validate();
      bcData = await queryZkClassMessagePC({ time: form.datetime, productFloor: form.inputValue });
      if (form.radio == '分') {
        barData = await queryAll({ time: form.datetime, productFloor: form.inputValue });
        analysisData = await queryCount({ time: form.datetime, productFloor: form.inputValue });
        if (analysisData) analysisData = analysisData.reverse();
        let eqResult = await queryEqPC({ time: form.datetime, productFloor: form.inputValue });
        let eqDataResult = clearData(eqResult);
        eqData.times = eqDataResult?.times2 || [];
        eqData.data = eqDataResult?.data || [];
      } else {
        barData = await queryAll2({ time: form.datetime, productFloor: form.inputValue });
        analysisData = await queryCount2({ time: form.datetime, productFloor: form.inputValue });
        if (analysisData) analysisData = analysisData.reverse();
        let eqResult = await queryEqPC2({ time: form.datetime, productFloor: form.inputValue });
        let eqDataResult = clearData(eqResult);
        eqData.times = eqDataResult?.times2 || [];
        eqData.data = eqDataResult?.data || [];
      }
      barData = barData.reverse();
    } catch (err) {
      console.log('err', err);
    }
  }
  // 重置
  function reset(e) {
    form.inputValue = '';
    form.datetime = '';
    formRef.value.resetFields();
  }
  function clearData(rawData) {
    // 首先，我们将原始数据按照时间进行分组
    if (!rawData || rawData.includes(null)) return;
    rawData = rawData.reverse();
    const groupedByTime = rawData.reduce((acc, group) => {
      group.forEach((item) => {
        const time = item.time.split(':')[0] + ':' + item.time.split(':')[1];
        if (!acc[time]) {
          acc[time] = {};
        }
        // 使用 tagName 作为键，pvValue 作为值
        acc[time][item.tagName] = item.pvValue;
      });
      return acc;
    }, {});
    console.log('groupedByTime', groupedByTime);

    // 接下来，我们提取时间和数据，并转换为所需的格式
    const times = Object.keys(groupedByTime).map((time) => time.split(':')[0] + ':' + time.split(':')[1]); // 只取时和分
    console.log(times);
    const names = ['烂瓶类', '调试问题类', '玻璃液问题类', '规格尺寸类', '变形类', '其他类'];
    const data = Object.keys(groupedByTime[times[0]]).map((tagName, i) => {
      // 初始化数组以存储每个 tagName 在不同时间点的 pvValue
      return [names[i], ...times.map((t) => (groupedByTime[t] ? groupedByTime[t][tagName] || 0 : 0))];
    });

    let times2 = times.map((v) => formatDate(v));
    return {
      times2,
      data,
    };
  }

  function formatDate(dateStr) {
    const date = new Date(dateStr);
    let hours = date.getHours().toString().padStart(2, '0');
    return hours;
  }
</script>

<style lang="less" scoped>
  .main {
    min-height: 100%;
    background-image: url('@/assets/images/dashbord-bg.png');
    background-repeat: no-repeat; /* 不重复背景图片 */
    background-size: cover; /* 图片覆盖整个元素 */
    background-position: center; /* 图片居中显示 */
  }

  .atable {
    :deep(.ant-table-cell-row-hover) {
      background: #195a93 !important;
    }
  }

  .myTable {
    width: 100%;
    color: #9ccae3;
    font-size: 20px;
    background: #0f1f34;
    th {
      background: #0a3157;
      line-height: 42px;
      border: 1px solid #1e5680;
    }
    td {
      border: 1px solid #1e5680;
      padding: 10px; /* 为单元格添加内边距 */
      text-align: center; /* 文字水平居中 */
      vertical-align: middle; /* 文字垂直居中 */
    }
  }

  .myTable1 {
    width: 100%;
    color: #3fa6ff;
    font-size: 18px;
    background: #0b1628;
    border: 1px solid #2572b3;
    th {
      background: #0a3157;
      line-height: 42px;
      border: 1px solid #1e5680;
    }
    td {
      color: #fff;
      padding: 10px; /* 为单元格添加内边距 */
      text-align: center; /* 文字水平居中 */
      vertical-align: middle; /* 文字垂直居中 */
    }
    td:nth-child(odd) {
      background-color: #174c7c;
    }
    td:nth-child(even) {
      background-color: #195a93;
    }
  }

  :deep(.ant-table-thead > tr > th) {
    background-color: #0b1628; /* 设置表头背景色 */
    color: #3fa6ff !important;
  }
</style>
